package com.liutt.cloud.sentinel;

import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;


/**
 * 熔断降级
 *
 * @author liuyuantao
 */
@RestController
@Slf4j
public class DegradeRuleController {

    /**
     * 熔断慢调用
     *
     * @return
     */
    @GetMapping("/helloDegrade1")
    @SentinelResource(value = "HELLO_DEGRADE1", blockHandler = "exceptionHandler")
    public String hello1() {
        ThreadUtil.sleep(RandomUtil.randomLong(1000, 2000));
        return "Hello Sentinel helloDegrade1";

    }

    /**
     * 熔断慢调用
     *
     * @return
     */
    @GetMapping("/helloDegrade2")
    @SentinelResource(value = "HELLO_DEGRADE2", blockHandler = "exceptionHandler")
    public String hello2() {
        int randomInt = RandomUtil.randomInt();
        if (randomInt % 2 == 0) {
            throw new RuntimeException("异常了");
        }
        return "Hello Sentinel helloDegrade2";

    }

    /**
     * @return
     */
    @GetMapping("/helloDegrade3")
    @SentinelResource(value = "HELLO_DEGRADE3", blockHandler = "exceptionHandler")
    public String hello3() {
        int randomInt = RandomUtil.randomInt();
        if (randomInt % 2 == 0) {
            throw new RuntimeException("异常了");
        }
        return "Hello Sentinel helloDegrade3";

    }

    public String exceptionHandler(BlockException e) {
        log.info("系统熔断进行了降级");
        e.printStackTrace();
        return "系统熔断,进行了降级";
    }


}
